<script setup lang="ts">
import {nextTick, ref, watch} from 'vue'
import SelectMedicineBasic from './SelectMedicineBasic.vue'
import {SelectMedicineEmit, SelectMedicinePopoverProps} from "@/component/select-medicine/types.ts";
import {MedicineData} from "@/api/medicine";
import {omit} from "lodash";

const props = withDefaults(defineProps<SelectMedicinePopoverProps>(), {
  isAuto: true,
  width: 1200,
  trigger: 'click',
  triggerKeys: () => {
    return ['Esc']
  }
})
const visible = ref<boolean>(false)
const $emit = defineEmits<SelectMedicineEmit>()

watch(
    () => props.value,
    (val) => {
      if (val && val !== '' && !visible.value) {
        visible.value = true
      }
    },
    {immediate: true}
)

const handleOpen = () => {
  if (props.value && props.value !== '' && !visible.value) {
    visible.value = true
  }
}
const handleClose = () => {
  visible.value = false
}
const handleCallback = (row: MedicineData) => {
  $emit('selectionChange', row)
  nextTick(() => {
    if (props.isAuto) {
      handleClose()
    }
  })
}
defineExpose({
  handleOpen,
  handleClose
})
</script>

<template>
  <el-popover
      :visible="visible"
      v-bind="Object.assign(omit(props, 'modelValue'), $attrs)"
  >
    <template #reference>
      <div @click="handleOpen">
        <slot name="reference"></slot>
      </div>
    </template>
    <SelectMedicineBasic v-bind="props" @callback="handleCallback"/>
  </el-popover>
</template>

<style scoped>

</style>